using System.Collections;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;

public class PlayerCtrl : MonoBehaviour
{
    public float moveForce = 500f;
    public float JumpForce = 300f;
    public float maxSpeed = 5.0f;
    private Rigidbody2D player;
    private bool bFaceRight = true;
    private Transform mGrandCheck;
    private bool bJump = false;
    // Start is called before the first frame update
    void Start()
    {
        mGrandCheck = transform.Find("GrandCheck");    
        player= GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    private void FixedUpdate()
    {
        float h = Input.GetAxis("Horizontal");
        if(h*player.velocity.x < maxSpeed)
        {
            player.AddForce(h * Vector2.right * moveForce);
        }
        if(Mathf.Abs(player.velocity.x) > maxSpeed) 
        {
            player.velocity = new Vector2(Mathf.Sign(player.velocity.x) * maxSpeed,player.velocity.y);
        }

        if (bFaceRight && h < 0)
        {
            flip();   
        }
        else if (!bFaceRight && h > 0)
                flip();
        if (bJump)
        {
            player.AddForce(Vector2.up * JumpForce);
            bJump = false;
        }
    }
    void Update()
    {
        if (Physics2D.Linecast(transform.position, mGrandCheck.position, 1 << LayerMask.NameToLayer("ground")))
        {
            if (Input.GetButtonDown("Jump"))
                bJump = true;
        }

    }
    void flip()
    {
        Vector3 theScale= player.transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
        bFaceRight = !bFaceRight;
    }
}
